package org.tictactoe;

import org.omg.CORBA.*;
import org.tictactoe.corba.*;

public class TictactoeServiceImpl extends TictactoeServicePOA
{
	private ORB orb;
	private int playerCount;
	private int[][] board;
	private Step lastStep;
	private boolean isStarted;
	
	public TictactoeServiceImpl() {
		playerCount = 0;
		isStarted = false;
	}
	
	public void setORB(ORB orb_val) {
		    orb = orb_val; 
	}
	
	public int startGame() {
		if (playerCount == 0) {
			board = new int[3][3];
			for (int i=0; i<3; i++)
				for (int j=0; j<3; j++)
					board[i][j] = 0;
			lastStep = new Step(-1,-1,2);
			isStarted = false;
			playerCount+=1;
			return playerCount;
		} else if (playerCount == 1) {
			isStarted = true;
			playerCount+=1;
			return playerCount;
		}
		return playerCount + 1;
	}
	
	public void endGame(int id) {
		playerCount -= 1;
	}
	
	public Step getLastStep() {
		return lastStep;
	}
	
	public boolean makeStep(Step myStep) {
		if (lastStep.team == myStep.team) return false;
		if ((myStep.row < 0) || (myStep.row > 2)) return false;
		if ((myStep.col < 0) || (myStep.col > 2)) return false; 		
		if (board[myStep.row][myStep.col] == 0) {
			board[myStep.row][myStep.col] = myStep.team;
			lastStep = myStep;
			return true;
		}
		else return false;
	}
	
	public boolean isStarted() {
		return isStarted;
	}
	
	public int isEnded() {
		for (int i=0; i<3; i++)
			if ((board[i][0] == board[i][1]) && (board[i][1] == board[i][2]) && (board[i][0] != 0)) return board[i][0];
		for (int i=0; i<3; i++)
			if ((board[0][i] == board[1][i]) && (board[1][i] == board[2][i]) && (board[0][i] != 0)) return board[0][i];
		if ((board[0][0] == board[1][1]) && (board[1][1] == board[2][2]) && (board[0][0] != 0)) return board[0][0];
		if ((board[0][2] == board[1][1]) && (board[1][1] == board[2][0]) && (board[0][2] != 0)) return board[0][2];
		if (playerCount != 2) return 4;
		for (int i=0; i<3; i++)
			for (int j=0; j<3; j++)
				if (board[i][j] == 0) return 0;		
		return 3;
	}

	
}
